package com.example.chuntiao.cophook.mytools;

import android.app.Activity;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.example.chuntiao.cophook.beans.InvitInfo;
import com.example.chuntiao.cophook.beans.Org;
import com.example.chuntiao.cophook.beans.Person;
import com.example.chuntiao.cophook.enums.UpdateState;
import com.example.chuntiao.cophook.exception.LogInException;
import com.example.chuntiao.cophook.exception.NewUserException;
import com.example.chuntiao.cophook.exception.RepeatException;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;

/**
 * Created by chuntiao on 17-7-28.
 */

public class HttpTool {

    public static final int CODE_ORGS = 0;
    public static final int CODE_PEOPLES = 1;

    public static final int CODE_A_INVITE_NUM = 2;
    public static final int CODE_REFRESH_INVIT_NUM = 3;
    public static final int CODE_QIUTE_ORG = 4;
    public static final int CODE_ACCESSIBLE_CHOICES = 5;

    public static final int UPLOAD_OEG_IMG = 0;
    public static final int UPLOAD_PEOPLE_IMG = 1;

    public static final int CODE_UPDATE_ORG=0;
    public static final int CODE_UPDATE_INVITE_LIMIT_TIME=1;

    public static String sendOkHttpRequest(Activity activity, int requestCode, String oid) throws IOException {
        MyApp app = (MyApp) activity.getApplication();
        OkHttpClient client = app.getClient();
        Request.Builder builder = new Request.Builder();

        switch (requestCode) {
            case CODE_ORGS:
                builder.url(MyApp.HOST_S_URL + "GetOrgs");
                break;

            case CODE_PEOPLES:
                builder.url(MyApp.HOST_S_URL + "GetPeoples");
                break;

            case CODE_A_INVITE_NUM:
                builder.url(MyApp.HOST_S_URL + "GetInvitNum")
                        .post(new FormBody.Builder()
                                .add("oid", oid)
                                .build()
                        );
                break;

            case CODE_REFRESH_INVIT_NUM:
                builder.url(MyApp.HOST_S_URL + "RefreshInvite")
                        .post(new FormBody.Builder()
                                .add("oid", oid)
                                .build()
                        );
                break;

            case CODE_QIUTE_ORG:
                builder.url(MyApp.HOST_S_URL + "QuitOrg")
                        .post(new FormBody.Builder()
                                .add("oid", oid)
                                .build())
                        .build();
                break;

            case CODE_ACCESSIBLE_CHOICES:
                builder.url(MyApp.HOST_S_URL + "AccessibleChoices")
                        .post(new FormBody.Builder()
                                .build())
                        .build();

        }


        Request request = builder.build();
        Response response = client.newCall(request).execute();

        if (!Boolean.parseBoolean(response.header("success")))
            if (HttpTool.senOkHttpLogIn(activity, app.getUid(), app.getPasswd())) {
                response.close();
                response = client.newCall(request).execute();
            } else
                throw new LogInException("登录失败");

        String jsonStr = response.body().string();
        response.close();

        return jsonStr;
    }

    public static boolean sendOkHttpJoinOrg(Activity activity, InvitInfo info) throws IOException {

        MyApp app = (MyApp) activity.getApplication();
        OkHttpClient client = app.getClient();
        Request request = new Request.Builder()
                .url(MyApp.HOST_S_URL + "Join")
                .post(new FormBody.Builder()
                        .add("tagUid", info.getUid())
                        .add("tagOid", info.getOid())
                        .add("tagInvitNum", info.getInvitNum())
                        .build())
                .build();

        Response response = client.newCall(request).execute();

        if (!Boolean.parseBoolean(response.header("success"))) {
            response.close();

            if (senOkHttpLogIn(activity, app.getUid(), app.getPasswd()))
                response = client.newCall(request).execute();
            else
                throw new LogInException("登录失败，请手动登录");
        }


        boolean repeat = Boolean.parseBoolean(response.header("repeat_record"));
        boolean joined = Boolean.parseBoolean(response.header("joined"));
        response.close();

        if (repeat)
            throw new RepeatException("记录重复");


        return joined;

    }

    public static boolean senOkHttpLogIn(Activity activity, String uid, String passwd) throws IOException {

        MyApp app = (MyApp) activity.getApplication();
        OkHttpClient client = app.getClient();

        if (app.getUid() == null || app.getUid().equals("") || app.getPasswd() == null || app.getPasswd().equals(""))
            throw new NewUserException("新用户");

        RequestBody form = new FormBody.Builder()
                .add("uid", uid)
                .add("passwd", passwd)
                .build();

        Request request = new Request.Builder()
                .url(MyApp.HOST_S_URL + "LogIn")
                .post(form)
                .build();
        Response response = client.newCall(request).execute();

        if (response == null)
            return false;
        else {
            synchronized (app.getLookObj()) {
                app.setLogedIn(true);
                app.setLastLogIn(System.currentTimeMillis());
            }

            boolean successOrNot = Boolean.parseBoolean(response.header("success"));
            response.close();

            return successOrNot;
        }

    }

    public static boolean sendOkHttpSignUp(Activity activity, Person newMan, String passwd) throws IOException {

        MyApp app = (MyApp) activity.getApplication();
        OkHttpClient client = app.getClient();

        RequestBody body = new FormBody.Builder()
                .add("uname", newMan.getName())
                .add("uid", newMan.getUid())
                .add("phone1", newMan.getPhone1())
                .add("phone2", newMan.getPhone2())
                .add("locate", newMan.getLocate())
                .add("passwd", passwd)
                .build();

        Request request = new Request.Builder()
                .post(body)
                .url(MyApp.HOST_S_URL + "SignUp")
                .build();

        Response response = client.newCall(request).execute();
        boolean repeat = Boolean.parseBoolean(response.header("repeat"));
        response.close();

        if (repeat)
            throw new RepeatException("uid repeats");

        return true;
    }


    public static int sendOkHttpUpload(Activity activity, @NonNull Bitmap bitmap, int requestCode, String oid) throws IOException {
        MyApp app = (MyApp) activity.getApplication();
        OkHttpClient client = app.getClient();

        final MediaType type = MediaType.parse("image/*");
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] byteArray = stream.toByteArray();

        RequestBody fileBody = RequestBody.create(type, byteArray);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "theFile", fileBody)
                .build();


        Request request = null;
        if (requestCode == UPLOAD_OEG_IMG) {
            request = new Request.Builder()
                    .url(MyApp.HOST_S_URL + "UpLoad")
                    .post(requestBody)
                    .addHeader("imgType", "org")
                    .addHeader("oid", oid)
                    .build();
        } else if (requestCode == UPLOAD_PEOPLE_IMG) {
            request = new Request.Builder()
                    .url(MyApp.HOST_S_URL + "UpLoad")
                    .post(requestBody)
                    .addHeader("imgType", "people")
                    .build();
        }
        Response response = client.newCall(request).execute();
        if (!Boolean.parseBoolean(response.header("success")))
            if (HttpTool.senOkHttpLogIn(activity, app.getUid(), app.getPasswd())) {
                response.close();
                response = client.newCall(request).execute();
            } else
                throw new LogInException("登录失败");

        int imgVer = Integer.parseInt(response.header("img_ver"));
        response.close();
        return imgVer;

    }

    @Nullable
    public static String sendOkHttpNewOrg(Activity activity, String oname, String intro) throws IOException {
        MyApp mApp = (MyApp) activity.getApplication();
        OkHttpClient client = mApp.getClient();

        RequestBody body = new FormBody.Builder()
                .add("oname", oname)
                .add("intro", intro)
                .build();
        Request request = new Request.Builder()
                .url(MyApp.HOST_S_URL + "NewOrg")
                .post(body)
                .build();

        Response response = client.newCall(request).execute();

        if (!Boolean.parseBoolean(response.header("success"))) {
            response.close();
            if (senOkHttpLogIn(activity, mApp.getUid(), mApp.getPasswd()))
                response = client.newCall(request).execute();
            else
                throw new LogInException("登录失败，请手动登录");
        }

        boolean repeat = Boolean.parseBoolean(response.header("oid_repeat"));
        if (repeat)
            throw new RepeatException("组织id重复");//TODO 组织ID对用户来说好像没啥意义
        boolean added = Boolean.parseBoolean(response.header("added"));
        String oid = response.header("oid");

        response.close();
        return added ? oid : null;
    }

    public static UpdateState sendOkHttpUpDatePersonInfo(Activity activity, String uname, String phone1, String phone2, String locate) throws IOException {
        MyApp app = (MyApp) activity.getApplication();
        OkHttpClient client = app.getClient();

        Request request = new Request.Builder()
                .url(MyApp.HOST_S_URL + "UpdateInfo")
                .post(new FormBody.Builder()
                        .add("uname", uname)
                        .add("phone1", phone1)
                        .add("phone2", phone2)
                        .add("locate", locate)
                        .build()
                )
                .build();

        Response response = client.newCall(request).execute();
        if (!Boolean.parseBoolean(response.header("success")))
            if (HttpTool.senOkHttpLogIn(activity, app.getUid(), app.getPasswd())) {
                response.close();
                response = client.newCall(request).execute();
            } else
                throw new LogInException("登录失败");

        String result = response.body().string();
        response.close();

        if (result.equals("updated_true"))
            return UpdateState.UPDATED;
        else if (result.equals("updated_nothing"))
            return UpdateState.NOTHING;

        return UpdateState.FAIL;
    }
    public static UpdateState sendOkHttpUpDateOrg(Activity activity, int CODE, Org o ,int time) throws IOException {

        MyApp app = (MyApp) activity.getApplication();
        OkHttpClient client = app.getClient();

        Request request=null;
        switch (CODE){
            case CODE_UPDATE_ORG:
                request=new Request.Builder()
                        .url(MyApp.HOST_S_URL+"UpdateOrg")
                        .post(new FormBody.Builder()
                                .add("oid",o.getOid())
                                .add("oname",o.getOname())
                                .add("open",""+o.isOpen())
                                .add("intro",o.getIntro())
                                .build())
                        .build();
                break;
            case CODE_UPDATE_INVITE_LIMIT_TIME:
                request=new Request.Builder()
                        .url(MyApp.HOST_S_URL+"UpdateLimitTime")
                        .post(new FormBody.Builder()
                                .add("oid",o.getOid())
                                .add("limitTime",""+time)
                                .build())
                        .build();
                break;
        }


        Response response = client.newCall(request).execute();
        if (!Boolean.parseBoolean(response.header("success")))
            if (HttpTool.senOkHttpLogIn(activity, app.getUid(), app.getPasswd())) {
                response.close();
                response = client.newCall(request).execute();
            } else
                throw new LogInException("登录失败");

        String result = response.body().string();
        response.close();

        if ("updated_true".equals(result))
            return UpdateState.UPDATED;
        else if ("updated_nothing".equals(result))
            return UpdateState.NOTHING;

        return UpdateState.FAIL;
    }


    /**
     *
     * @param activity
     * @param phone 传入请求发短信的手机好
     * @return  发送成功为true
     * @throws IOException
     */
    public static boolean reqSms(Activity activity,String phone) throws IOException {
        MyApp app = (MyApp) activity.getApplication();
        OkHttpClient client = app.getClient();
        Request request=new Request.Builder()
                .url(MyApp.HOST_S_URL+"ReqSmsNum")
                .post(new FormBody.Builder()
                        .add("phone",phone)
                        .build()
                )
                .build();
        Response response=client.newCall(request).execute();
        boolean found=Boolean.parseBoolean(response.header("found"));
        if(!found)
            throw new NewUserException("未检测到此用户");

        return Boolean.parseBoolean(response.header("send_succeed")) ;//服务器成功请求短信并成功收到　云端反馈　短信
    }
    public static boolean updatePass(Activity activity, String checkNum, String pass) throws IOException {
        MyApp app = (MyApp) activity.getApplication();
        OkHttpClient client = app.getClient();
        Request request=new Request.Builder()
                .url(MyApp.HOST_S_URL+"UpdatePass")
                .post(new FormBody.Builder()
                        .add("sms_num",checkNum)
                        .add("pass",pass)
                        .build()
                )
                .build();
        Response response=client.newCall(request).execute();
        boolean replaced=Boolean.parseBoolean(response.header("replaced"));
        response.close();
        return replaced;
    }
}
